import { CAHNGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM, CHECK_BOX_HANDLER, CENSUS_CHECK_NUM, DELETE_COMPLETED
 } from './actionTypes';
const initState = {
    value:'',
    list:[
        {
            name:'1',
            isCompleted:false
        }
    ],
    activeNum:0
}
export default (state=initState,action) => {
    let newState;
    switch(action.type){
        case CAHNGE_INPUT_VALUE:
            return Object.assign({},state,{value:action.value});
        case ADD_TODO_ITEM:
            newState = JSON.parse(JSON.stringify(state));
            if(newState.value.trim() === '') return newState;
            newState.list.push({name:newState.value,isCompleted:false});
            newState.value = '';
            return newState;
        case DELETE_TODO_ITEM:
            newState = JSON.parse(JSON.stringify(state));
            newState.list.splice(action.index,1);
            return newState;
        case CHECK_BOX_HANDLER:
            newState = JSON.parse(JSON.stringify(state));
            newState.list[action.index].isCompleted = !newState.list[action.index].isCompleted;
            return newState;
        case CENSUS_CHECK_NUM:
            newState = JSON.parse(JSON.stringify(state));
            let num=0;
            newState.list.forEach(element => {
                if(element.isCompleted) num++
            });
            return Object.assign({},state,{activeNum:num});
        case DELETE_COMPLETED:
            newState = JSON.parse(JSON.stringify(state));
            for(var i = newState.list.length-1;i>=0;i-- ){
                var item = newState.list[i]
                if(item.isCompleted){
                    newState.list.splice(i,1)
                }
            }
            return newState;
        default:
            return state
    }
}